<?php

namespace app\admin\controller;

use think\Db;
use think\facade\Request;

class Block extends Common
{
    public function index()
    {
        if (Request::isAjax()) {
            $key = input('post.key');
            $page = input('page') ? input('page') : 1;
            $pageSize = input('limit') ? input('limit') : config('pageSize');
            $list = db('block')
                ->where('title', 'like', "%" . $key . "%")
                ->order('sort')
                ->paginate(['list_rows' => $pageSize, 'page' => $page])
                ->toArray();
            foreach ($list['data'] as $k => $v) {
                $list['data'][$k]['create_time'] = date('Y-m-d H:s', $v['create_time']);
            }
            return ['code' => 0, 'msg' => '获取成功!', 'data' => $list['data'], 'count' => $list['total']];
        }
        return $this->fetch();
    }
    
    public function edit()
    {
        if (Request::isAjax()) {
            $data = input('post.');
            if ($data['id'] > 0) {
                db('block')->where('id', $data['id'])->update($data);
            } else {
                unset($data['id']);
                db('block')->insert($data);
            }
            $result['code'] = 1;
            $result['msg'] = '操作成功!';
            $result['url'] = url('index');
            return $result;
        } else {
            $id = input('id');
            $info = db('block')->where(['id' => $id])->find();
            $this->assign('info', $info);
            $this->assign('title', lang('edit') . lang('block'));
            return $this->fetch('edit');
        }
    }
    
    public function del()
    {
        db('block')->where('id', input('post.id'))->delete();
        return ['code' => 1, 'msg' => '删除成功！'];
    }
    
    public function blockOrder()
    {
        $data = input('post.');
        if (db('block')->update($data) !== false) {
            return ['msg' => '操作成功！', 'url' => url('index'), 'code' => 1];
        } else {
            return ['code' => 0, 'msg' => '操作失败！'];
        }
    }
    
    public function delAll()
    {
        $map['id'] = ['in', input('param.ids/a')];
        db('block')->where($map)->delete();
        $result['msg'] = '删除成功！';
        $result['code'] = 1;
        $result['url'] = url('index');
        return $result;
    }
}